#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称: feedback_management_api.py
完整存储路径: backend/api/admin/feedback_management_api.py
功能说明:
    用户反馈管理API接口，用于管理员查看和回复用户反馈
    
路由说明:
    - GET /api/admin/feedback - 获取反馈列表
    - GET /api/admin/feedback/<id> - 获取反馈详情
    - POST /api/admin/feedback/<id>/reply - 回复反馈
    - PUT /api/admin/feedback/<id>/status - 更新反馈状态
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from functools import wraps
from datetime import datetime
from backend.models.feedback import Feedback, FeedbackReply
from backend.models.user import User
from backend.infrastructure.database import db
from backend.services.unified_log_service import log_service
from sqlalchemy import and_, or_

feedback_management_api = Blueprint('feedback_management_api', __name__)

# 管理员权限装饰器
def admin_required(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        from flask_jwt_extended import get_jwt
        claims = get_jwt()
        roles = claims.get('roles', [])
        if 'admin' not in roles:
            return jsonify({'success': False, 'message': '仅管理员可操作'}), 403
        return fn(*args, **kwargs)
    return wrapper

@feedback_management_api.route('/api/admin/feedback', methods=['GET'])
@jwt_required()
@admin_required
def list_feedback():
    """获取用户反馈列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        status = request.args.get('status')
        priority = request.args.get('priority')
        search_term = request.args.get('search', '').strip()
        
        # 构建查询
        query = Feedback.query
        
        # 状态筛选
        if status:
            query = query.filter(Feedback.status == status)
        
        # 优先级筛选
        if priority:
            query = query.filter(Feedback.priority == priority)
        
        # 搜索功能
        if search_term:
            query = query.join(User).filter(
                or_(
                    Feedback.title.like(f'%{search_term}%'),
                    Feedback.content.like(f'%{search_term}%'),
                    User.real_name.like(f'%{search_term}%'),
                    User.nickname.like(f'%{search_term}%'),
                    User.username.like(f'%{search_term}%')
                )
            )
        
        # 分页查询
        pagination = query.order_by(Feedback.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        feedback_list = []
        for feedback in pagination.items:
            feedback_dict = feedback.to_dict()
            # 添加用户信息
            if feedback.user:
                feedback_dict['user_name'] = feedback.user.name
                feedback_dict['user_phone'] = feedback.user.mobile
            
            # 添加回复数量
            reply_count = FeedbackReply.query.filter_by(feedback_id=feedback.id).count()
            feedback_dict['reply_count'] = reply_count
            
            feedback_list.append(feedback_dict)
        
        return jsonify({
            'success': True,
            'data': {
                'feedback': feedback_list,
                'pagination': {
                    'page': page,
                    'per_page': per_page,
                    'total': pagination.total,
                    'pages': pagination.pages,
                    'has_next': pagination.has_next,
                    'has_prev': pagination.has_prev
                }
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取反馈列表失败: {str(e)}'
        }), 500

@feedback_management_api.route('/api/admin/feedback/<int:feedback_id>', methods=['GET'])
@jwt_required()
@admin_required
def get_feedback_detail(feedback_id):
    """获取反馈详情"""
    try:
        feedback = Feedback.query.get_or_404(feedback_id)
        
        feedback_dict = feedback.to_dict()
        
        # 添加用户信息
        if feedback.user:
            feedback_dict['user_info'] = {
                'id': feedback.user.id,
                'name': feedback.user.name,
                'phone': feedback.user.mobile,
                'email': feedback.user.email
            }
        
        # 获取回复列表
        replies = FeedbackReply.query.filter_by(feedback_id=feedback_id).order_by(FeedbackReply.created_at.asc()).all()
        feedback_dict['replies'] = [reply.to_dict() for reply in replies]
        
        return jsonify({
            'success': True,
            'data': feedback_dict
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取反馈详情失败: {str(e)}'
        }), 500

@feedback_management_api.route('/api/admin/feedback/<int:feedback_id>/reply', methods=['POST'])
@jwt_required()
@admin_required
def reply_feedback(feedback_id):
    """回复用户反馈"""
    try:
        feedback = Feedback.query.get_or_404(feedback_id)
        data = request.get_json()
        current_user_id = get_jwt_identity()
        
        if not data.get('content'):
            return jsonify({
                'success': False,
                'message': '回复内容不能为空'
            }), 400
        
        # 创建回复记录
        reply = FeedbackReply(
            feedback_id=feedback_id,
            user_id=current_user_id,
            content=data['content'],
            is_admin_reply=data.get('is_internal', False)  # 是否为内部备注
        )
        
        db.session.add(reply)
        
        # 如果不是内部备注，更新反馈状态为已回复
        if not reply.is_admin_reply and feedback.status == 'pending':
            feedback.status = 'processing'
        
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='REPLY',
            table_name='feedback_replies',
            record_id=feedback_id,
            details=f'回复反馈: {feedback.title}'
        )
        
        # TODO: 这里可以发送邮件或推送通知给用户
        
        return jsonify({
            'success': True,
            'data': reply.to_dict(),
            'message': '回复成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'回复失败: {str(e)}'
        }), 500

@feedback_management_api.route('/api/admin/feedback/<int:feedback_id>/status', methods=['PUT'])
@jwt_required()
@admin_required
def update_feedback_status(feedback_id):
    """更新反馈状态"""
    try:
        feedback = Feedback.query.get_or_404(feedback_id)
        data = request.get_json()
        current_user_id = get_jwt_identity()
        
        new_status = data.get('status')
        if not new_status:
            return jsonify({
                'success': False,
                'message': '状态不能为空'
            }), 400
        
        # 验证状态值
        valid_statuses = ['pending', 'processing', 'resolved', 'closed']
        if new_status not in valid_statuses:
            return jsonify({
                'success': False,
                'message': '无效的状态值'
            }), 400
        
        old_status = feedback.status
        feedback.status = new_status
        
        # 如果状态变为已解决，记录解决时间
        if new_status == 'resolved':
            feedback.resolved_at = datetime.utcnow()
        
        feedback.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='UPDATE_STATUS',
            table_name='feedback',
            record_id=feedback_id,
            details=f'反馈状态从 {old_status} 更改为 {new_status}'
        )
        
        return jsonify({
            'success': True,
            'data': feedback.to_dict(),
            'message': '状态更新成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'更新状态失败: {str(e)}'
        }), 500

@feedback_management_api.route('/api/admin/feedback/statistics', methods=['GET'])
@jwt_required()
@admin_required
def get_feedback_statistics():
    """获取反馈统计信息"""
    try:
        # 按状态统计
        statuses = ['pending', 'processing', 'resolved', 'closed']
        status_stats = {}
        for status in statuses:
            count = Feedback.query.filter_by(status=status).count()
            status_stats[status] = count
        
        # 按优先级统计
        priority_stats = {}
        priorities = ['low', 'normal', 'high', 'urgent']
        for priority in priorities:
            count = Feedback.query.filter_by(priority=priority).count()
            priority_stats[priority] = count
        
        # 本月新增反馈数量
        from datetime import datetime, timedelta
        current_month = datetime.now().replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        monthly_count = Feedback.query.filter(Feedback.created_at >= current_month).count()
        
        # 待处理反馈数量
        pending_count = Feedback.query.filter_by(status='pending').count()
        
        return jsonify({
            'success': True,
            'data': {
                'status_statistics': status_stats,
                'priority_statistics': priority_stats,
                'monthly_count': monthly_count,
                'pending_count': pending_count,
                'total_count': sum(status_stats.values())
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取统计信息失败: {str(e)}'
        }), 500

@feedback_management_api.route('/api/admin/feedback/stats', methods=['GET'])
@jwt_required()
@admin_required
def get_feedback_stats():
    """获取反馈统计信息"""
    try:
        # 按状态统计
        statuses = ['pending', 'processing', 'resolved', 'closed']
        status_stats = {}
        for status in statuses:
            count = Feedback.query.filter_by(status=status).count()
            status_stats[status] = count
        
        return jsonify({
            'success': True,
            'data': {
                'pending': status_stats.get('pending', 0),
                'processing': status_stats.get('processing', 0),
                'resolved': status_stats.get('resolved', 0),
                'closed': status_stats.get('closed', 0)
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取统计信息失败: {str(e)}'
        }), 500
